<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Schema::defaultStringLength(191);

        

        if (env('IS_DEBUG_SQL', false)) {
            DB::listen(
                function ($sql) {
                    foreach ($sql->bindings as $i => $binding) {
                        if ($binding instanceof \DateTime) {
                            $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                        } else {
                            if (is_string($binding)) {
                                $sql->bindings[$i] = "'$binding'";
                            }
                        }
                    }
            
                    // Insert bindings into query
                    $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            
                    $query = vsprintf($query, $sql->bindings);
            
                    // Save the query to file
                    $logFile = fopen(
                        storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
                        'a+'
                    );
                    fwrite($logFile, date('Y-m-d H:i:s') . '['.$sql->time.'ms]: ' . $query . PHP_EOL);
                    fclose($logFile);
                }
            );
        }
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('mobile', function ($attribute, $value, $parameters) {
            $g = "/^1[1-9]\d{9}$/";
            if(preg_match($g, $value)){
                return true;
            }
            return false;
        }, '手机号码无效');

        Validator::extend('strin', function ($attribute, $value, $parameters) {
            $params = implode(",", $parameters);
            $values = explode(",", $params);
            if ($value) {
                return in_array($value, $values);
            }
            return false;
        }, '必须在给定的列表中');

        Validator::extend('idcard', function ($attribute, $value, $parameters) {
            if ($value) {
                return is_idcard($value);
            }
            return false;
        }, '身份证号码无效');
        if (env('ADMIN_HTTPS', false)) {
            URL::forceScheme('https');
        }
    }
}
